/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model.dao;

import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import model.pojo.Turma;
import model.pojo.Historico;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;
import model.dao.exceptions.NonexistentEntityException;
import model.pojo.Aluno;
import model.pojo.Disciplina;
import model.pojo.Professor;

/**
 *
 * @author leonidia
 */
public class DisciplinaJpaController implements DisciplinaInterface {

    public DisciplinaJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    @Override
    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public Integer procuraDisciplina(String nome,DaoBase daoBase,Professor professor){
        Integer contador =0;
        DisciplinaJpaController disciplinaJpaController = new DisciplinaJpaController(null, daoBase.returnFactory());
        List<Disciplina> listaDisciplina = disciplinaJpaController.findDisciplinaEntities();
        for (Disciplina item : listaDisciplina) {
            if (item.getTurma().getProfessor().getNome() == professor.getNome()) {
                if (item.getTurma().getDisciplina().getNome() == nome) {
                    contador++;
                }
            }
        }
        return contador;
    }

    @Override
    public void create(Disciplina disciplina) {
        if (disciplina.getHistorico() == null) {
            disciplina.setHistorico(new ArrayList<Historico>());
        }
        if (disciplina.getAluno() == null) {
            disciplina.setAluno(new ArrayList<Aluno>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Turma turma = disciplina.getTurma();
            if (turma != null) {
                turma = em.getReference(turma.getClass(), turma.getId());
                disciplina.setTurma(turma);
            }
            Collection<Historico> attachedHistorico = new ArrayList<Historico>();
            for (Historico historicoHistoricoToAttach : disciplina.getHistorico()) {
                historicoHistoricoToAttach = em.getReference(historicoHistoricoToAttach.getClass(), historicoHistoricoToAttach.getId());
                attachedHistorico.add(historicoHistoricoToAttach);
            }
            disciplina.setHistorico(attachedHistorico);
            Collection<Aluno> attachedAluno = new ArrayList<Aluno>();
            for (Aluno alunoAlunoToAttach : disciplina.getAluno()) {
                alunoAlunoToAttach = em.getReference(alunoAlunoToAttach.getClass(), alunoAlunoToAttach.getId());
                attachedAluno.add(alunoAlunoToAttach);
            }
            disciplina.setAluno(attachedAluno);
            em.persist(disciplina);
            if (turma != null) {
                Disciplina oldDisciplinaOfTurma = turma.getDisciplina();
                if (oldDisciplinaOfTurma != null) {
                    oldDisciplinaOfTurma.setTurma(null);
                    oldDisciplinaOfTurma = em.merge(oldDisciplinaOfTurma);
                }
                turma.setDisciplina(disciplina);
                turma = em.merge(turma);
            }
            for (Historico historicoHistorico : disciplina.getHistorico()) {
                Disciplina oldDisciplinaOfHistoricoHistorico = historicoHistorico.getDisciplina();
                historicoHistorico.setDisciplina(disciplina);
                historicoHistorico = em.merge(historicoHistorico);
                if (oldDisciplinaOfHistoricoHistorico != null) {
                    oldDisciplinaOfHistoricoHistorico.getHistorico().remove(historicoHistorico);
                    oldDisciplinaOfHistoricoHistorico = em.merge(oldDisciplinaOfHistoricoHistorico);
                }
            }
            for (Aluno alunoAluno : disciplina.getAluno()) {
                alunoAluno.getDisciplina().add(disciplina);
                alunoAluno = em.merge(alunoAluno);
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    @Override
    public void edit(Disciplina disciplina) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Disciplina persistentDisciplina = em.find(Disciplina.class, disciplina.getId());
            Turma turmaOld = persistentDisciplina.getTurma();
            Turma turmaNew = disciplina.getTurma();
            Collection<Historico> historicoOld = persistentDisciplina.getHistorico();
            Collection<Historico> historicoNew = disciplina.getHistorico();
            Collection<Aluno> alunoOld = persistentDisciplina.getAluno();
            Collection<Aluno> alunoNew = disciplina.getAluno();
            if (turmaNew != null) {
                turmaNew = em.getReference(turmaNew.getClass(), turmaNew.getId());
                disciplina.setTurma(turmaNew);
            }
            Collection<Historico> attachedHistoricoNew = new ArrayList<Historico>();
            for (Historico historicoNewHistoricoToAttach : historicoNew) {
                historicoNewHistoricoToAttach = em.getReference(historicoNewHistoricoToAttach.getClass(), historicoNewHistoricoToAttach.getId());
                attachedHistoricoNew.add(historicoNewHistoricoToAttach);
            }
            historicoNew = attachedHistoricoNew;
            disciplina.setHistorico(historicoNew);
            Collection<Aluno> attachedAlunoNew = new ArrayList<Aluno>();
            for (Aluno alunoNewAlunoToAttach : alunoNew) {
                alunoNewAlunoToAttach = em.getReference(alunoNewAlunoToAttach.getClass(), alunoNewAlunoToAttach.getId());
                attachedAlunoNew.add(alunoNewAlunoToAttach);
            }
            alunoNew = attachedAlunoNew;
            disciplina.setAluno(alunoNew);
            disciplina = em.merge(disciplina);
            if (turmaOld != null && !turmaOld.equals(turmaNew)) {
                turmaOld.setDisciplina(null);
                turmaOld = em.merge(turmaOld);
            }
            if (turmaNew != null && !turmaNew.equals(turmaOld)) {
                Disciplina oldDisciplinaOfTurma = turmaNew.getDisciplina();
                if (oldDisciplinaOfTurma != null) {
                    oldDisciplinaOfTurma.setTurma(null);
                    oldDisciplinaOfTurma = em.merge(oldDisciplinaOfTurma);
                }
                turmaNew.setDisciplina(disciplina);
                turmaNew = em.merge(turmaNew);
            }
            for (Historico historicoOldHistorico : historicoOld) {
                if (!historicoNew.contains(historicoOldHistorico)) {
                    historicoOldHistorico.setDisciplina(null);
                    historicoOldHistorico = em.merge(historicoOldHistorico);
                }
            }
            for (Historico historicoNewHistorico : historicoNew) {
                if (!historicoOld.contains(historicoNewHistorico)) {
                    Disciplina oldDisciplinaOfHistoricoNewHistorico = historicoNewHistorico.getDisciplina();
                    historicoNewHistorico.setDisciplina(disciplina);
                    historicoNewHistorico = em.merge(historicoNewHistorico);
                    if (oldDisciplinaOfHistoricoNewHistorico != null && !oldDisciplinaOfHistoricoNewHistorico.equals(disciplina)) {
                        oldDisciplinaOfHistoricoNewHistorico.getHistorico().remove(historicoNewHistorico);
                        oldDisciplinaOfHistoricoNewHistorico = em.merge(oldDisciplinaOfHistoricoNewHistorico);
                    }
                }
            }
            for (Aluno alunoOldAluno : alunoOld) {
                if (!alunoNew.contains(alunoOldAluno)) {
                    alunoOldAluno.getDisciplina().remove(disciplina);
                    alunoOldAluno = em.merge(alunoOldAluno);
                }
            }
            for (Aluno alunoNewAluno : alunoNew) {
                if (!alunoOld.contains(alunoNewAluno)) {
                    alunoNewAluno.getDisciplina().add(disciplina);
                    alunoNewAluno = em.merge(alunoNewAluno);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = disciplina.getId();
                if (findDisciplina(id) == null) {
                    throw new NonexistentEntityException("The disciplina with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    @Override
    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Disciplina disciplina;
            try {
                disciplina = em.getReference(Disciplina.class, id);
                disciplina.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The disciplina with id " + id + " no longer exists.", enfe);
            }
            Turma turma = disciplina.getTurma();
            if (turma != null) {
                turma.setDisciplina(null);
                turma = em.merge(turma);
            }
            Collection<Historico> historico = disciplina.getHistorico();
            for (Historico historicoHistorico : historico) {
                historicoHistorico.setDisciplina(null);
                historicoHistorico = em.merge(historicoHistorico);
            }
            Collection<Aluno> aluno = disciplina.getAluno();
            for (Aluno alunoAluno : aluno) {
                alunoAluno.getDisciplina().remove(disciplina);
                alunoAluno = em.merge(alunoAluno);
            }
            em.remove(disciplina);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    @Override
    public List<Disciplina> findDisciplinaEntities() {
        return findDisciplinaEntities(true, -1, -1);
    }

    @Override
    public List<Disciplina> findDisciplinaEntities(int maxResults, int firstResult) {
        return findDisciplinaEntities(false, maxResults, firstResult);
    }

    private List<Disciplina> findDisciplinaEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Disciplina as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    @Override
    public Disciplina findDisciplina(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Disciplina.class, id);
        } finally {
            em.close();
        }
    }

    @Override
    public int getDisciplinaCount() {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select count(o) from Disciplina as o");
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
}
